import Joi from 'joi';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { ConfigEnum } from './enum/config.enum';

// 实体
import { User } from './user/user.entity';
import { UserProfile } from './user/userProfile.entity';
import { Roles } from './roles/roles.entity';
import { Logs } from './logs/logs.entity';

import { LogsModule } from './logs/logs.module';


@Module({
  imports: [
    // 获取获取环境变量 
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env.development`,
      validationSchema: Joi.object({
        [ConfigEnum.DB]: Joi.string().valid('mysql', 'postgres'),
        [ConfigEnum.DB_HOST]: Joi.string().required(),
        [ConfigEnum.DB_PORT]: Joi.number().required(),
        [ConfigEnum.DB_USERNAME]: Joi.string().required(),
        [ConfigEnum.DB_PASSWORD]: Joi.string().required(),
        [ConfigEnum.DB_DATABASE]: Joi.string().required(),
      }),
    }),
    
    // 配置TypeORM, 数据库连接信息
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: configService.get(ConfigEnum.DB),
        host: configService.get(ConfigEnum.DB_HOST),
        port: configService.get(ConfigEnum.DB_PORT),
        username: configService.get(ConfigEnum.DB_USERNAME),
        password: configService.get(ConfigEnum.DB_PASSWORD),
        database: configService.get(ConfigEnum.DB_DATABASE),
        entities: [User, UserProfile, Roles, Logs],
        synchronize: true,
        logging: true,
      } as TypeOrmModuleOptions),
    }),
    // TypeOrmModule.forRoot({
    //   type: 'mysql',
    //   host: 'localhost',
    //   port: 3306,
    //   username: 'root',
    //   password: 'aptx4869',
    //   database: 'sky_take_out',
    //   entities: [],
    //   synchronize: true,
    // }),
    UserModule,
    LogsModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
